package com.golang.api.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

public class JwtHS256Parser {
    private static final String SECRET_KEY = "12345678901234567890";
    private static final Key KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());

    public static Claims parseTokenWithHS256(String token) {
        return Jwts.parserBuilder()
               .setSigningKey(KEY)
               .build()
               .parseClaimsJws(token)
               .getBody();
    }

    public static String createTokenWithHS256(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(KEY) // 默认使用 HS256
                .compact();
    }


    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", "exampleUser");
        String token = createTokenWithHS256(claims);
        System.out.println("Token: " + token);
        // 这里假设 token 是之前使用 HS256 算法生成的
        try {
            Claims result = parseTokenWithHS256(token);
            System.out.println("username: " + result.get("username"));
        } catch (Exception e) {
            System.err.println("解析 Token 出错: " + e.getMessage());
        }
    }
}